import { HttpError, toSuccess, useEntityManager } from "@sker/core";
import { AutoUser, KsDevice, KsLiveRoomLog } from "@sker/entities";
import { useData } from "@sker/runtime";
import { z } from "zod";

export default async () => {
    const input = z.object({
        token: z.string()
    });
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) throw new HttpError(`参数错误`)
        if (user.replace_mobile) user.mobile = user.replace_mobile
        const start = new Date()
        start.setMinutes(0)
        start.setHours(0)
        start.setSeconds(0)
        start.setMilliseconds(0)
        const list = await m.createQueryBuilder()
            .select('sum(log.count)', 'count')
            .addSelect(`date_trunc('hour', log.open_time)`, 'open_hour')
            .addSelect(`max(log.open_time)`, 'open_time')
            .addSelect('log.pkg', 'pkg')
            .from(KsLiveRoomLog, 'log')
            .leftJoin(KsDevice, 'device', 'device.uuid=log.uuid')
            .where('log.open_time>=:open_time', { open_time: start })
            .andWhere('log.status=:status', { status: '1' })
            .andWhere('device.owner=:owner', { owner: user.mobile })
            .groupBy('log.pkg').addGroupBy('open_hour').orderBy('open_hour', 'ASC').execute()
        return toSuccess(list)
    })
}
